﻿using B.S.DataBase.MyProject.Domain.基础设置;
using B.S.DataBase.MyProject.Domain.知识管理;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.KnowledgeManagement;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.KnowledgeManagement
{
    /// <summary>
    /// 我的知识查询命令处理方法
    /// </summary>
    public class GetKnowledgeCommandHandler : IRequestHandler<GetKnowledgeCommand, ApiPaging<KnowledgeManagements>>
    {
        /// <summary>
        /// sqlsugar
        /// </summary>
        private readonly SqlSugarContext sugar;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="sugar"></param>
        public GetKnowledgeCommandHandler(SqlSugarContext sugar)
        {
            this.sugar = sugar;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<KnowledgeManagements>> Handle(GetKnowledgeCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<KnowledgeManagements> result = new ApiPaging<KnowledgeManagements>();
            try
            {
                var list = sugar.db.Queryable<KnowledgeManagements>().Where(x => !x.IsDel);
                if (!string.IsNullOrEmpty(request.Theme))
                {
                    list = list.Where(x => x.Theme.Contains(request.Theme));

                }
                if (!string.IsNullOrEmpty(request.ApplicableDisease))
                {
                    list = list.Where(x => x.ApplicableDisease.Contains(request.ApplicableDisease));
                }
                if (request.KnowledgeStatus != null)
                {
                    list = list.Where(x => x.KnowledgeStatus == request.KnowledgeStatus);
                }
                list = list.OrderByDescending(x => x.KnowledgeID).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
                int TotalCount = list.Count();
                int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.pageSize);
                result.list = list.ToList();
                result.TotalCount = TotalCount;
                result.TotalPage = TotalPage;
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"查询知识管理时发生异常: {ex.Message}");
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
            }
            return await Task.FromResult(result);
        }



    }

}
